/* A moz-remote service for direct javascript evaluation
  Copyright (C) 2006 by Lukas Loehrer
  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA

  Author: Lukas Loehrer <loehrerl [at] gmx [dot] net>
*/

var logger = module.require("package", "lib/filelogger").logger;

// This is a service which can emit events
try {
	logger.debug("jshell: About to load event service.");
var EventService = module.require("class", "event_service");
var inheritor = new EventService();
logger.debug("jshell: event_service loaded.");
} catch (e) {
	logger.error("Failed to load event service: " + e, e);
}

var repl = module.require('class', 'js_shell/repl');

function constructor(name, remote, context) {
	EventService.call(this, name, remote);
	this._repl = new repl(this, context);
	this._remote = remote;

	this._outputBuffer = "";

	// Set up events specific for this class
	this._events["outputAvailable"] =true;
}

function loadFile(url) {
	return this._repl.load(url);
}

function evaluate(code){
	if(code.match(/^\s*$/)) {
		return "";
	}

	try {
		var result = this._repl.load('data:application/x-javascript,' +
								encodeURIComponent(code));
		result = result || "";
		return result.toString();
	} catch (e) {
		//his.print(_formatStackTrace1(e));
        
		return  ('!!! ' + e.toString() + '\n');
	}
}


// sends output event to client
function print(output) {
	this._outputBuffer += output;
	this._fireEvent("outputAvailable", this._outputBuffer.length);
}


function getPendingOutput() {
	var tmp = this._outputBuffer;
	this._outputBuffer = "";
	return tmp;
}

